package com.foreknow.controller;

import com.foreknow.bean.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器向客户端响应的内容的类型
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端发送请求的字符编码集
        req.setCharacterEncoding("utf-8");
        //通过getWriter方法获取PrintWriter输出流对象，主要用于在网页上输出结果
        PrintWriter out = resp.getWriter();
        //获取请求参数
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");

        //调用Service中的方法
        GuestbookService service = new GuestbookServiceImpl();

        Guestbook gb = new Guestbook();
        gb.setName(name);
        gb.setPhone(phone);
        gb.setEmail(email);
        gb.setTitle(title);
        gb.setContent(content);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        gb.setCreatedtime(sdf.format(new Date()));

        boolean isRight = service.save(gb);
        if(isRight) {
            //out.println("<a href='get'>query all</a>");
            //转发资源到GetMessageServlet
            //req.getRequestDispatcher("get").forward(req,resp);
            //重定向
            resp.sendRedirect("http://www.163.com");
        }else {
            out.println("save error......");
        }
    }
}
